import React from 'react';
import {BrowserRouter, Navigate, Outlet, Route, Routes} from 'react-router-dom';
import routes from './routes';

const renderRoute = (routes: any) => {
    if (!Array.isArray(routes)) {
        return null;
    }
    return (
        routes.map((route, index) => {
            if (route.redirect) {
                return (
                    <Route
                        key={route.path || index}
                        path={route.path}
                        element={<Navigate to={route.redirect}/>}/>
                );
            }
            return (
                <Route
                    key={route.path || index}
                    path={route.path}
                    element={route.component ? <route.component {...route} /> : <Outlet/>}
                >
                    {renderRoute(route.children)}
                </Route>
            );
        })
    );
};

const AppRouter: React.FC<any> = () => {
    return (
        <BrowserRouter basename={'/'}>
            <Routes>
                {renderRoute(routes)}
            </Routes>
        </BrowserRouter>
    );
};

export default AppRouter;
